package com.roger.ndtplayer.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.roger.ndtplayer.commom.bus.Bus
import com.roger.ndtplayer.commom.bus.USER_LOGIN_STATE_CHANGED

abstract class BaseDBFragment<VM : BaseViewModel, DB : ViewDataBinding> : BaseFragment() {

    lateinit var mDataBind: DB
    private var lazyLoaded = false
    protected lateinit var mViewModel: VM

    //界面状态管理者
//    protected lateinit var uiStatusManger: LoadService<*>

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        initViewModel()
        mDataBind = DataBindingUtil.inflate<ViewDataBinding>(
            inflater,
            layoutId,
            container,
            false
        ) as DB
        mDataBind.lifecycleOwner = this
        return mDataBind.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        observe()
    }

    override fun onResume() {
        super.onResume()
        // 实现懒加载
        if (!lazyLoaded) {
            lazyLoadData()
            lazyLoaded = true
        }
    }

    /**
     * 初始化ViewModel
     */
    private fun initViewModel() {
        mViewModel = ViewModelProvider(this, ViewModelProvider.NewInstanceFactory()).get(viewModelClass())
    }

    /**
     * 获取ViewModel的class
     */
    abstract fun viewModelClass(): Class<VM>


    /**
     * 订阅，LiveData、Bus
     */
    open fun observe() {
        // 登录失效，跳转登录页
        mViewModel.loginStatusInvalid.observe(viewLifecycleOwner, {
            if (it) {
                Bus.post(USER_LOGIN_STATE_CHANGED, false)
//                ActivityHelper.startActivity(LoginActivity::class.java)
            }
        })
        mViewModel.showDialog.observe(viewLifecycleOwner, {
            if (it) {
                showProgressDialog(mViewModel.dialogMsg.value.toString())
            } else {
                dismissProgressDialog()
            }
        })
//        mViewModel.showEmptyView.observe(viewLifecycleOwner, {
//            if (it) {
//                showEmptyView()
//            }
//        })
//        mViewModel.showNoNetView.observe(viewLifecycleOwner, {
//            if (it) {
//                showErrorView()
//            }
//        })
//        mViewModel.showSuccess.observe(viewLifecycleOwner,{
//            if(it){
//                uiStatusManger.showSuccess()
//            }
//        })
    }


}
